/**
 * @author Daniel
 */


(function($) {

	var DWB = {};
	
	DWB.Tools = {
		Rect: 'rect'
		, Brush: 'brush'
		, Line: 'line'
		, Square: 'square'
		, Circle: 'circle'
		, Ellipse: 'ellipse'
		, Polygon: 'polygon'
		, Text: 'text'
		, Eraser: 'eraser'
	};
	
	DWB.accName = '';
	
	var Chat = {};
	
	Chat.socket = null;
	
	Chat.connect = function(host) {
	    if ('WebSocket' in window) {
	        Chat.socket = new WebSocket(host);
	    } else if ('MozWebSocket' in window) {
	        Chat.socket = new MozWebSocket(host);
	    } else {
	        console.log('Error: WebSocket is not supported by this browser.');
	        return;
	    }
	
	    Chat.socket.onopen = function () {
	        console.log('Info: WebSocket connection opened.');
	    };
	
	    Chat.socket.onclose = function () {
	        console.log('Info: WebSocket closed.');
	    };
	
	    Chat.socket.onmessage = function (message) {
	    	try {
	    		var msg = JSON.parse(message.data);
	    		if (msg.type == 'login') {
	    			DWB.accName = msg.accName;
	    		}
	    		else if (msg.type == 'txtMsg') {
	    			var message = msg.sender + ': ' + msg.content;
	    			$('#messageDisplayArea').val($('#messageDisplayArea').val() + '\n' + message);
	    		} 
	    		else if (msg.type == 'sysMsg') {
	    			var message = msg.content;
	    			$('#messageDisplayArea').val($('#messageDisplayArea').val() + '\n' + message);	    			
	    		}
	    		else if (msg.type == 'action') {
	    			var action = [msg.content];
	    			dwbWidget.dwb('playback', action, msg.sender);
	    		}
	    	} catch (error) {
	    		console.log(error);
	    	}
	    };
	};
	
	Chat.initialize = function() {
	    if (window.location.protocol == 'http:') {
	        Chat.connect('ws://' + window.location.host + ':8080/dwb/ws');
	    } else {
	        Chat.connect('wss://' + window.location.host + ':8080/dwb/ws');
	    }
	};
	
	Chat.sendMessage = function(message) {
	    Chat.socket.send(message);
	};
	
	var dwbWidget;
	
	$(document).ready(function() {
		initStage();
		bindEvents();
		Chat.initialize();
		activeTool(DWB.Tools.Brush);
	});
	
	function initStage() {
		dwbWidget = $('.stage-container').dwb({
			'newAction': function(event, action) {
				
				var layerId;
				if (action.type == 'undo') { //自己undo的信息发送出去前要替换layerId信息才能让对方正确执行
					layerId = action.layerId;
					action.layerId = DWB.accName;
				}
				
				var msg = {type:'action', content:action, 'sender':DWB.accName};
				Chat.sendMessage(JSON.stringify(msg));
				
				if (action.type == 'undo') { //发送消息后将layerId改回来
					action.layerId = layerId;
				}
			}
		});
	}
	
	function enableDragDropImage() {
		$('.stage-container').filedrop({
			paramname:'pic',
			
			maxfiles: 100,
	    	maxfilesize: 100,
			url: '/dwb/upload',
			
			uploadFinished:function(i,file,response){
				dwbWidget.dwb('insertImage', "/" + response.url);
			},
			
			beforeEach: function(file){
				if(!file.type.match(/^image\//)){
					alert('Only images are allowed!');
					return false;
				}
			}
		});		
	}
	
	function bindEvents() {
		
		window.addEventListener("paste", function(e){
			$.dealPasteImg(e, function(pastedImage){
				dwbWidget.dwb('insertImage', pastedImage.src, function(imgId) {
					$.convertImgToBlob(pastedImage, 'png', function(blob) {
						$.upload('/dwb/upload', blob, {}, null, function(data) {
							var url = JSON.parse(data).url;
							dwbWidget.dwb('insertImage', "/" + url, imgId);
						});							
					});
				});
			}, $('#div4firefoxPaste'));
		});
		
		enableDragDropImage();
		
		var fillColorMenu = $('#fillColorMenu');
		var fillColorSubMenu = fillColorMenu.next();
		var strokeColorMenu = $('#strokeColorMenu');
		var strokeColorSubMenu = strokeColorMenu.next();
		var shapeMenu = $('#shapeMenu');
		var shapeSubMenu = shapeMenu.next();
		var displayImgMenu = $('#displayImgMenu');
		var displayImgSubPanel = displayImgMenu.next();
		var strokeWithMenu = $('#strokeWithMenu');
		var strokeWithSubMenu = strokeWithMenu.next();
		var fontsizeMenu = $('#fontsizeMenu');
		var fontsizeSubMenu = fontsizeMenu.next();
		var sysFuncMenu = $('#sysFuncMenu');
		var sysFuncSubMenu = sysFuncMenu.next();
		
		var drawRectTool = $('#drawRectTool');
		var displayImgTool = $('#displayImgTool');
		var drawBrushTool = $('#drawBrushTool');
		var drawLineTool = $('#drawLineTool');
		var drawSquareTool = $('#drawSquareTool');
	    var drawCircleTool = $('#drawCircleTool');
	    var drawEllipseTool = $('#drawEllipseTool');
	    var drawPolygonTool = $('#drawPolygonTool');
	    var drawTextTool = $('#drawTextTool');
	    var undoTool = $('#undoTool');
	    var eraserTool = $('#eraserTool');
	    var toImageTool = $('#toImageTool');
		var playbackTool = $('#playbackTool');
		var fastPlaybackTool = $('#fastPlaybackTool');	    
	    
	    var txtMsgInput = $('#txtMsgInput');
	    var messageDisplayArea = $('#messageDisplayArea');
	    
	    txtMsgInput.bind('keydown', function(event) {
	    	if (event.keyCode == 13) {
	    		var msg = txtMsgInput.val();
	    		if (msg) {
			    	messageDisplayArea.val(messageDisplayArea.val() + '\n' + 'me: ' +  msg);
			    	txtMsgInput.val('');	    			
	    			msg = JSON.stringify({type:"txtMsg", content:msg, sender:DWB.accName});
			    	Chat.sendMessage(msg);
	    		}
	    	}
	    });
	    
	    fillColorMenu.bind({
	    	'click': function() {
	    		fillColorSubMenu.toggle();
	    	}
	    });
		fillColorSubMenu.bind({
			'mouseover' : function() {
				fillColorSubMenu.show();
			},
			'mouseout' : function() {
				fillColorSubMenu.hide();
			}
		});
		fillColorSubMenu.find('span').each(function(idx, item) {
			$(item).bind('click', function() {
				var colorVal = $(item).attr('color');
				dwbWidget.dwb('setFillColor', colorVal);
				fillColorMenu.css('backgroundColor', colorVal);
				fillColorSubMenu.hide();
			});
		});
		
	    strokeColorMenu.bind({
	    	'click': function() {
	    		strokeColorSubMenu.toggle();
	    	}
	    });
		strokeColorSubMenu.bind({
			'mouseover' : function() {
				strokeColorSubMenu.show();
			},
			'mouseout' : function() {
				strokeColorSubMenu.hide();
			}
		});
		strokeColorSubMenu.find('span').each(function(idx, item) {
			$(item).bind('click', function() {
				var colorVal = $(item).attr('color');
				dwbWidget.dwb('setStrokeColor', colorVal);
				strokeColorMenu.css('backgroundColor', colorVal);
				strokeColorSubMenu.hide();
			});
		});
		
	    strokeWithMenu.bind({
	    	'click': function() {
	    		strokeWithSubMenu.toggle();
	    	}
	    });
		strokeWithSubMenu.bind({
			'mouseover' : function() {
				strokeWithSubMenu.show();
			},
			'mouseout' : function() {
				strokeWithSubMenu.hide();
			}
		});
		strokeWithSubMenu.find('span.icon-base').each(function(idx, item) {
			$(item).bind('click', function() {
				var widthVal = $(item).attr('width');
				dwbWidget.dwb('setStrokeWidth', widthVal);
				strokeWithMenu.find('span').attr('class', $(item).attr('class'));
				strokeWithSubMenu.hide();
			});
		});
		
	    fontsizeMenu.bind({
	    	'click': function() {
	    		fontsizeSubMenu.toggle();
	    	}
	    });
		fontsizeSubMenu.bind({
			'mouseover' : function() {
				fontsizeSubMenu.show();
			},
			'mouseout' : function() {
				fontsizeSubMenu.hide();
			}
		});
		fontsizeSubMenu.find('li').each(function(idx, item) {
			$(item).bind('click', function() {
				var fontsize = $(item).find('span[value]').attr('value');
				dwbWidget.dwb('setFontSize', fontsize);
				fontsizeMenu.find('span').text(fontsize + 'px');
				fontsizeSubMenu.hide();
			});
		});
		
	    shapeMenu.bind({
	    	'click': function() {
	    		shapeSubMenu.toggle();
	    	}
	    });
		shapeSubMenu.bind({
			'mouseover' : function() {
				shapeSubMenu.show();
			},
			'mouseout' : function() {
				shapeSubMenu.hide();
			}
		});	
		
	    displayImgMenu.bind({
	    	'click': function() {
	    		displayImgSubPanel.toggle();
	    	}
	    });
	    displayImgSubPanel.find('input[type="text"]').bind('keydown', function(event) {
	    	if (event.keyCode == 13) {
	    		displayImgTool.trigger('click');
	    	}
	    });
	    
	    sysFuncMenu.bind({
	    	'click': function() {
	    		sysFuncSubMenu.toggle();
	    	}
	    });
	    sysFuncSubMenu.bind({
			'mouseover' : function() {
				sysFuncSubMenu.show();
			},
			'mouseout' : function() {
				sysFuncSubMenu.hide();
			}
	    });
		
		drawRectTool.bind('click', function(event) {
			activeTool(DWB.Tools.Rect);
			shapeMenu.find('span').attr('class', 'icon-base rect-icon');
		});
		drawBrushTool.bind('click', function(event) {
			activeTool(DWB.Tools.Brush);
			shapeMenu.find('span').attr('class', 'icon-base pencil-icon');
		});
		drawLineTool.bind('click', function(event) {
			activeTool(DWB.Tools.Line);
			shapeMenu.find('span').attr('class', 'icon-base line-icon');
		});
		drawSquareTool.bind('click', function(event) {
			activeTool(DWB.Tools.Square);
			shapeMenu.find('span').attr('class', 'icon-base square-icon');
		});
		drawCircleTool.bind('click', function(event) {
			activeTool(DWB.Tools.Circle);
			shapeMenu.find('span').attr('class', 'icon-base circle-icon');
		});
		drawEllipseTool.bind('click', function(event) {
			activeTool(DWB.Tools.Ellipse);
			shapeMenu.find('span').attr('class', 'icon-base ellipse-icon');
		});
		drawPolygonTool.bind('click', function(event) {
			// activeTool(DWB.Tools.Polygon);
			alert('TODO');
		});
		drawTextTool.bind('click', function(event) {
			activeTool(DWB.Tools.Text);
			shapeMenu.find('span').attr('class', 'icon-base text-icon');
		});
		
		displayImgTool.bind('click', function(event) {
			var imgUrl = displayImgSubPanel.find('input[type="text"]').val();
			dwbWidget.dwb('insertImage', imgUrl);
			displayImgSubPanel.hide();
		});		
		playbackTool.bind('click', function(event) {
			dwbWidget.dwb('playback');
		});
		fastPlaybackTool.bind('click', function(event) {
			dwbWidget.dwb('playback', null, null, true);
		});
		
		undoTool.bind('click', function(event) {
			dwbWidget.dwb('undo');
		});
		
		eraserTool.bind('click', function(event) {
			activeTool(DWB.Tools.Eraser);
		});
		
		toImageTool.bind('click', function(event) {
			dwbWidget.dwb('toImage', function(img) {
				window.open(img.src, '_blank');
			});
		});
	}
	
	function activeTool(toolName) {
		if (toolName == DWB.Tools.Rect) {
			dwbWidget.dwb('activeRectDraw');
		} else if (toolName == DWB.Tools.Brush) {
			dwbWidget.dwb('activeBrushDraw');
		} else if (toolName == DWB.Tools.Line) {
			dwbWidget.dwb('activeLineDraw');
		} else if (toolName == DWB.Tools.Square) {
			dwbWidget.dwb('activeSquareDraw');
		} else if (toolName == DWB.Tools.Circle) {
			dwbWidget.dwb('activeCircleDraw');
		} else if (toolName == DWB.Tools.Ellipse) {
			dwbWidget.dwb('activeEllipseDraw');
		} else if (toolName == DWB.Tools.Polygon) {
			dwbWidget.dwb('activePolygonDraw');
		} else if (toolName == DWB.Tools.Text) {
			dwbWidget.dwb('activeTextDraw');
		} else if (toolName == DWB.Tools.Eraser) {
			dwbWidget.dwb('activeEraser');
		}
	}
	
})(jQuery);
